/**
 * @param {number} element
 * @param {number} to
 * @param {number} duration
 * @param {Function} callback
 */
export function scrollTo(element: HTMLElement, to: number, duration: number, callback?: () => void): void {
  const start = element.scrollTop
  const change = to - start
  const increment = 20
  let currentTime = 0

  const animateScroll = () => {
    currentTime += increment
    const val = easeInOutQuad(currentTime, start, change, duration)
    element.scrollTop = val
    if (currentTime < duration) {
      setTimeout(animateScroll, increment)
    } else if (callback) {
      callback()
    }
  }

  animateScroll()
}

/**
 * @param {number} t
 * @param {number} b
 * @param {number} c
 * @param {number} d
 * @returns {number}
 */
function easeInOutQuad(t: number, b: number, c: number, d: number): number {
  t /= d / 2
  if (t < 1) {
    return c / 2 * t * t + b
  }
  t--
  return -c / 2 * (t * (t - 2) - 1) + b
} 